﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Pg.BioMedics.ASR.Client
{
    public partial class NewTaskForm : Form
    {
        public NewTaskForm()
        {
            InitializeComponent();
        }

        private void NewTaskForm_Load(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                DialogResult = DialogResult.Cancel;
                Close();
            }

            taskPriorityComboBox.SelectedIndex = 1;
            taskTypeComboBox.SelectedIndex = 0;
            taskNameTextBox.Text = Path.GetFileNameWithoutExtension(openFileDialog.FileName);
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void enqueueButton_Click(object sender, EventArgs e)
        {
            try
            {
                using (WebServices.ASRServiceClient client = new WebServices.ASRServiceClient())
                {
                    client.ClientCredentials.UserName.UserName = ClientCredentialsCache.GetInstance().Credential.UserName;
                    client.ClientCredentials.UserName.Password = ClientCredentialsCache.GetInstance().Credential.Password;

                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        using (FileStream inStream = File.Open(openFileDialog.FileName, FileMode.Open))
                        {
                            byte[] buffer = new byte[4192];
                            int length = 0;
                            while ((length = inStream.Read(buffer, 0, 4192)) > 0)
                                memoryStream.Write(buffer, 0, length);
                        }

                        memoryStream.Position = 0;
                        WebServices.Task task = client.EnqueueTask(taskNameTextBox.Text, taskTypeComboBox.SelectedItem as string, taskPriorityComboBox.SelectedItem as string, memoryStream.GetBuffer());

                        taskUniqueIdTextBox.Text = task.UniqueId;
                    }
                }

                taskNameTextBox.Enabled = false;
                taskPriorityComboBox.Enabled = false;
                taskTypeComboBox.Enabled = false;
                enqueueButton.Enabled = false;

                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }   
    }
}
